/**
 * 列选择器
 */
import { Input, Tree } from "antd";
import React, { useState, useEffect, Fragment } from "react";
import styles from "./index.less";
// import { queryUserFieldTree, updateBatch } from '@/services/fund'
import * as _ from "lodash";
import cn from "classnames";
import ex_icon from "@/assets/icons/rating-overview-arrow-white.png";
import grey_search from "@/assets/icons/icon-search_white.png";

interface ColumnSelectorProps {
  title?: string;
  columnOptions: any; // 列名
  checkedValues?: any; // 选中的列
  changeColumns?: ([]: any[]) => void; // 点击确认按钮
  changeCheckedKeys?: ([]: any[]) => void;
  changeCheckedIds?: ([]: any[]) => void;
  setPopoverVisible?: any;
  style?: any;
  visible: boolean;
  tableId: number;
  checkedKeys?: any; // 选中的节点
  searchTableFieldDTOList: any;
  treeResult: any; //树节点信息
  belong?: string; // 判断属于哪个模块，做特殊处理用
}

const { TreeNode } = Tree;

export const _generalTreeData = (
  data: any[],
  checks: string[],
  checksIds: string[],
  checksCols: string[],
  expends?: string[]
) => {
  const res: any[] = [];
  function _loopData(data) {
    if (!_.isEmpty(data)) {
      data.map((item) => {
        const obj = {
          title: item.title,
          id: item.id,
          key: item.pid + "_" + item.id + "_" + item.type,
          sorter: Boolean(item.sort),
          pid: item.pid,
          parentName: item.parentName,
          children: null,
          level: null,
          type: item.type,
        };
        if (!_.isEmpty(item.children)) {
          if (expends) {
            obj.parentKeys = expends.concat([obj.key]);
          } else {
            obj.parentKeys = [obj.key];
          }
          obj.children = _generalTreeData(
            item.children,
            checks,
            checksIds,
            checksCols,
            obj.parentKeys
          )?.res;
          res.push(obj);
        } else {
          //最末层叶子节点
          // if (item.checked) {
          checks.push(item.pid + "_" + item.id + "_" + item.type);
          (item.type || item.type === 0) && checksIds.push(item.type); //和升银约定id传树结构的type
          (item.type || item.type === 0) && checksCols.push(item.name); //选中的columns
          // console.log('checks',checks,'checksIds',checksIds);
          // }
          if (expends) {
            obj.parentKeys = expends.concat([obj.key]);
          } else {
            obj.parentKeys = [obj.key];
          }
          res.push(obj);
        }
      });
    }
  }
  _loopData(data);
  return { res, checks, checksIds, checksCols };
};

const ColumnSelector = (props: ColumnSelectorProps) => {
  const [selectedColumns, setSelectedColumns] = useState([]); // 选择显示的列

  const [treeData, setTreeData] = useState([]);
  const [treeDataOriginal, setTreeDataOriginal] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([] as string[]);
  // const [checkedKeys, setCheckedKeys] = useState([] as string[]);
  const [checkNodes, setCheckNodes] = useState([]);
  const [placeholderVal, setPlaceholder] = useState("搜索指标");
  const [searchVal, setSearchVal] = useState("");

  let {
    title,
    columnOptions,
    checkedValues,
    changeColumns,
    setPopoverVisible,
    visible,
    tableId,
    checkedKeys,
    changeCheckedKeys,
    searchTableFieldDTOList,
    changeCheckedIds,
    treeResult,
    belong,
  } = props;

  useEffect(() => {
    console.log("hhhhhhhh");
    if (!visible) return;

    const data = treeResult?.res;
    setTreeData(data);
    const copyData = _.cloneDeep(data);
    setTreeDataOriginal(copyData);
    // setCheckedKeys(checks)

    // queryUserFieldTree({ tableId, type: 2 }).then(res => {
    //   if (res?.code === '0') {
    //     if (!_.isEmpty(res?.data?.searchTableFieldDTOList)) {
    //       const checks: string[] = []
    //       const data = _generalTreeData(res?.data?.searchTableFieldDTOList, checks)
    //       setTreeData(data)
    //       const copyData = _.cloneDeep(data)
    //       setTreeDataOriginal(copyData)
    //       setCheckedKeys(checks)
    //     }
    //   }

    // })
  }, [treeResult]);

  const confirmColumns = () => {
    changeColumns && changeColumns();
    // const arr: string[] = []
    // if (!_.isEmpty(checkedKeys)) {
    //   checkedKeys.map(v => {
    //     const s = v.split('_')[2]
    //     if (s !== 'null') {
    //       arr.push(s)
    //     }
    //   })
    // }
    // // changeColumns && changeColumns(selectedColumns);
    // setPopoverVisible && setPopoverVisible(false);

    // handleSaveColumns(arr)
  };

  const getParentKey = (tree: any, val: any, parentKeys: any) => {
    if (!val) return;
    if (tree.title.indexOf(val) > -1) {
      if (tree.parentKeys) {
        tree.parentKeys.map((v) => {
          if (!parentKeys.includes(v)) {
            parentKeys.push(v);
          }
        });
      }
    }
    if (tree.children) {
      tree.children.map((item: any) => {
        getParentKey(item, val, parentKeys);
      });
    }
    return parentKeys;
  };

  const onChangeValues = (value?: string) => {
    setSearchVal(value);
    if (!value) {
      const arr: string[] = [];
      const rData = (data: any[]) => {
        data.map((v: any) => {
          if (v.children) {
            arr.push(v.key);
            rData(v.children);
          }
        });
      };
      rData(treeDataOriginal);
      setExpandedKeys(arr);
      return;
    }
    const parentKeys: any = [];
    treeDataOriginal.map((item: any) => {
      return getParentKey(item, value, parentKeys);
    });
    setExpandedKeys(parentKeys);
  };

  // 保存保存设置的列
  const handleSaveColumns = (data: string[]) => {
    // updateBatch({ tableId, ids: data }).then(res => {
    //   if (res?.code === '0' && res?.data) {
    //     changeColumns(checkNodes)
    //   }
    // })
  };

  const handleClickIcon = (a: any, e: any) => {
    const copyArr: string[] = _.cloneDeep(expandedKeys);
    const i: number = _.findIndex(copyArr, (k: string) => k === e.key);
    if (i === -1 && a) {
      copyArr.push(e.key);
    } else if (a) {
      copyArr.splice(i, 1);
    }
    setExpandedKeys(copyArr);
  };

  const onExpand = (expandedKeys, { expanded, node }) => {
    setExpandedKeys(expandedKeys);
  };

  const onCheck = (
    checkedKeys,
    { checked, checkedNodes, node, event, halfCheckedKeys }
  ) => {
    console.log("checkedKeys", checkedKeys, "checkedNodes", checkedNodes);
    // setCheckedKeys(checkedKeys)
    changeCheckedKeys &&
      changeCheckedKeys(checkedKeys?.length > 0 ? checkedKeys : []);
    changeCheckedIds &&
      changeCheckedIds(
        checkedNodes?.length > 0 ? checkedNodes.map((item) => item.type) : []
      );
    setCheckNodes(checkedNodes);
  };

  const titleClass = (node: any) =>
    cn({
      [styles.firstTitle]: belong !== "报表" && node.pid == null,
      [styles.title]: true,
      [styles.darkTitle]: true,
    });

  const tilteRender = (node: any) => {
    return <span className={titleClass(node)}>{node.title}</span>;
  };
  console.log(treeData);

  const renderTreeNodes = (data: any) => {
    if (data && data.length > 0) {
      return data.map((item) => {
        if (item.children && item.children.length > 0) {
          return (
            <TreeNode {...item}>{renderTreeNodes(item.children)}</TreeNode>
          );
        }
        return belong === "报表" ? (
          <TreeNode
            {...item}
            disabled={item.checked}
            className={item.checked ? "checked-node" : ""}
          />
        ) : (
          <TreeNode {...item} disabled={false} />
        );
      });
    }
    return null;
  };
  useEffect(() => {
    console.log(111111111, checkedKeys);
  }, [checkedKeys]);

  const loop = (data: any, parentKey?: string[]) =>
    data.map((item: any) => {
      const searchTxt = searchVal;
      let index = -1;
      let beforeStr = -1;
      let afterStr = -1;
      if (_.isString(item.title)) {
        index = item.title?.indexOf(searchTxt);
        beforeStr = item.title.substr(0, index);
        afterStr = item.title.substr(index + searchTxt.length);
      }
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span style={{ color: "#F8A456" }}>{searchTxt}</span>
            {afterStr}
          </span>
        ) : (
          <span>{item.title}</span>
        );
      if (item.children) {
        return {
          ...item,
          title,
          children: loop(item.children, parentKey?.concat([item.key])),
        };
      }
      return {
        ...item,
        title,
      };
    });

  return (
    <Fragment>
      <div className={styles.header}>
        <span className={styles.header_title}>{title}</span>
        <div className={styles.header_btn} onClick={confirmColumns} />
      </div>
      <div className={styles.treeBody}>
        <Input
          className={cn(
            styles.treeSearch,
            (!placeholderVal || searchVal) && styles.focusedInput
          )}
          prefix={<img src={grey_search} />}
          placeholder={placeholderVal}
          onFocus={() => setPlaceholder("")}
          onBlur={() => setPlaceholder("搜索指标")}
          onChange={(e) => onChangeValues(e.target.value)}
          value={searchVal}
        />
        <Tree
          titleRender={tilteRender}
          onClick={handleClickIcon}
          onExpand={onExpand}
          onCheck={onCheck}
          // selectedKeys={checkedKeys}
          // treeData={treeData}
          expandedKeys={expandedKeys}
          checkedKeys={checkedKeys}
          checkable
          className={cn(styles.customTree, styles.darkTree)}
          switcherIcon={<img src={ex_icon} alt="expend" />}
        >
          {renderTreeNodes(loop(treeData, []))}
        </Tree>
      </div>
    </Fragment>
  );
};
export default ColumnSelector;
